import { reqGetCakeInfo } from '../../api/cate'; // 导入接口
import { toast } from '../../utils/extendApi';
import { getStorage } from '../../utils/storage';
import {addBuyCar,nowBuy,selectBuycarhascount,updateCountCakeid} from "../../api/buycar";

Page({
    data: {
      count:1,//购买数量
      buttext:'加入购物车',//按钮文本
      product: {},// 商品详情
      evaluateUrl:"",
      showPopup: false, // 控制弹窗显示隐藏
      selectedWeight:'',
      userinfo:'',
      cakeid:'',
      cake:'',
      iflogin:'',//判断是否登录
    },
    //加入购物车数量
    changeCount(e){
      const { type } = e.currentTarget.dataset;
      let count=this.data.count;
      if (type === 'minus' && count > 1) {
        count--;
        //修改
        const buycar={
          "cakeid":this.data.cakeid,
          "cakesum":count
          }
          updateCountCakeid(buycar);
      } else if (type === 'plus') {
        if(count<3){
          count++;
        }
      }
      this.setData({
       count
      });
    },
    onShow(){
      this.setData({
        userinfo: getStorage("userinfo"),
        iflogin:getStorage("iflogin"),
      })
    },
    //获取购物车总数
    async getcountBuycar(cakeid){
        //根据蛋糕id查询购物车里是否已经有该商品
        const res=  await  selectBuycarhascount(cakeid);
        console.log("蛋糕",res);
        if(res.data.res!=null){
          this.setData({
            count:res.data.res
          })
        }
    },
      onLoad(options) {
        //数量恢复初始值
        this.setData({
          count:1,
          userinfo: getStorage("userinfo"),
          cakeid:options.cakeid,
          iflogin:getStorage("iflogin"),
         });
        const cakeid = options.cakeid; // 从 URL 参数获取 cakeId
        this.getcountBuycar(cakeid);
        if(!cakeid){
            console("cakeid不存在");
            toast({
                title:'参数错误',
                icon:'none'
            });
            return;
        }
        // 如果cakeid存在就赋值
        this.setData({
            evaluateUrl:`/pages/judge/judge?cakeid=${cakeid}`
        })
        this.getProductDetail(cakeid); // 调用接口获取详情
        // 设置导航栏样式（保持原有逻辑）
        wx.setNavigationBarColor({
          backgroundColor: '#FFB5C5',
          frontColor: '#000000',
          animation: { duration: 400, timingFunc: 'easeIn' }
        });
        wx.setNavigationBarTitle({ title: '详情页面 ' });
      },
      // 调用接口获取商品详情
      async getProductDetail(cakeid) {
        try {
            const res = await reqGetCakeInfo(cakeid);
            console.log("接口返回 data：", res.data);
            
            if (res && res.code === 200 && res.data && res.data.cakeById) { 
              this.setData({
                product: res.data.cakeById 
              });
            } else {
              throw new Error('商品详情数据异常');
            }
          } catch (err) {
          toast({ title: '商品详情加载失败', icon: 'none' });
          console.error(err);
        }
      },
    
      // 以下方法（guige、closePopup、selectWeight 等）保持不变...
      guige(e) {
        this.setData({ showPopup: true });
        const { type } = e.currentTarget.dataset;
        //判断点击的是立即购买或者加入购物车,根据不同的类型选择不同的按钮
        if(type==='addcar'){
          //加入购物车
          this.setData({
            buttext:"加入购物车"
          })
        }else if(type==='nowbuy'){
          //立即购买
          this.setData({
            buttext:"下一步"
          })
        }
      },
      closePopup() {
        this.setData({ showPopup: false });
      },
 
    selectWeight(e) {
      const value = e.currentTarget.dataset.value;
      console.log(value)
      this.setData({
        selectedWeight: value
      });
    },
    selectFilling(e) {
      const value = e.currentTarget.dataset.value;
      const option = this.data.fillingOptions.find(item => item.value === value);
      this.setData({
        selectedFilling: option
      });
    },
   
     async addToCart() {
      if(!this.data.iflogin){
        //跳转到登录页面
        toast({ title: '登录过后再进行此操作',duration:500});
        setTimeout(() => {
          // 新增地址成功后，返回地址
          wx.switchTab({
            url: '/pages/owner/owner',
          })
        }, 700);
        return;
      }
      // 这里添加加入购物车的逻辑，例如向购物车数组添加商品等
      console.log("已选规格：", this.data.selectedWeight,this.data.count);
      this.setData({
        showPopup: false
      });
      if(this.data.selectedWeight==''){
        toast({ title: '请选择规格',duration:500});
        return
      }
      let type=this.data.selectedWeight=='4英寸'?0:1
      //加入购物车
      const buycar={
        "userid":this.data.userinfo.userid,
        "cakeid":this.data.cakeid,
        "cakesum":this.data.count,
        "type":type
      }
      if(this.data.buttext==="下一步"){
        //立即购买接口
        const resp=await nowBuy(buycar);
        console.log(resp,"后端返回数据")
        this.setData({
          cake:resp.data.buyCarRequest
        })
        wx.navigateTo({
          url: '/pages/checkout/checkout',
        })
        return;
      }
      try{
      const res=await addBuyCar(buycar); 
      if(res.data.meg=='200'){
        console.log(res.data.meg,res.data.res>0)
        wx.switchTab({
          url: '/pages/cate/cate',
        })
      }else{
        toast({ title: '该商品数量已经购满' });
      }        
      }catch(error){
        toast({ title: '网络开了点小差，请稍后在式' });
        toast({ title: '登录异常，请稍后重试' });
      }
    }
  });